package top.psjj.news.dao;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import top.psjj.news.po.TType;
import top.psjj.news.utils.DataSourceUtils;

import java.sql.Connection;
import java.util.List;

/**
 * @Auther:小陈的Java
 */
public class TypeDao {
    private QueryRunner queryRunner = new QueryRunner();

    public List<TType> queryAll() throws Exception{
        Connection connection = DataSourceUtils.getConnection();
        String sql = "select id,type_name typeName from t_type order by id desc";
        BeanListHandler<TType> handler = new BeanListHandler<>(TType.class);
        List<TType> result = queryRunner.query(connection, sql, handler);
        return result;
    }

    public void add(TType type) throws Exception{
        String sql = "insert into t_type(type_name) value(?)";
        queryRunner.update(DataSourceUtils.getConnection(),sql,type.getTypeName());
    }

    public TType queryTypeById(int id) throws Exception{
        Connection connection = DataSourceUtils.getConnection();
        String sql = "select id,type_name typeName from t_type  where id=?";
        BeanHandler<TType> handler = new BeanHandler<>(TType.class);
        TType result = queryRunner.query(connection, sql,handler,id);
        return result;
    }
    public void update(TType type) throws Exception {
        String sql = "update t_type set type_name=? where id=?";
        queryRunner.update(DataSourceUtils.getConnection(),sql,type.getTypeName(),type.getId());
    }

    public void del(int id) throws Exception {
        String sql = "delete from t_type where id=?";
        queryRunner.update(DataSourceUtils.getConnection(),sql,id);
    }
}
